
(defun escape-quotes (string)
  (escape-single-quotes (escape-double-quotes string)))

(defun escape-single-quotes (string)
  (replace-regexp-in-string "'" "\\'" string nil 1))

(defun escape-double-quotes (string)
  (replace-regexp-in-string "\"" "\\\"" string nil 1))

(defun ruby-on-region (rubycode)
  "This function pipes the contents of the region to a ruby script and replaces\
the region with its output. 
'code' is a string containing the script."
  (save-excursion
    (shell-command-on-region (region-beginning) (region-end) 
                             (concat "ruby -e \"" 
                                     (escape-quotes rubycode) 
                                     "\"") 
                             -1)))


(defun textile-to-html-region ()
  "Convert textile markup in region to html. 
To make this work, you need the ruby interpreter to be in your system path. 
You will also need to have rubygems and redcloth installed."
  (interactive "*")
  (ruby-on-region "
require 'redcloth'
text = readlines.join
puts RedCloth.new(text).to_html
"))

(defun textile-to-bloghtml ()
  "This is an alternative to 'textile-to-html-region'.The html is 
   stripped a bit further so it looks better with a blog software 
   like twoday.net, which replaces newlines with <br> tags etc. "
  (interactive "*")
  (ruby-on-region "
require 'redcloth'
text = readlines.join
content = RedCloth.new(text).to_html
puts content.gsub(/\<[\\/]*p\>/,'')\
                 .gsub(/\n\b*\n/,'\n')\
                 .gsub(/\t/,'')
"))
